<template>
  <div class="container" >
      <div class="getInsurance">
            <i-cell title="证件类型:" required='required' class="cell-item content-item">
                <view slot="footer">
                    <radio-group class="footer" @change="cardChange">
                        <view class="radio-item">
                            <radio class="i-radio" color='#2d8cf0' v-model="idcard" checked='true'></radio>
                            <view class="i-radio-title">身份证</view>
                        </view>
                        <view class="radio-item">
                            <radio class="i-radio" color='#2d8cf0' v-model="other"></radio>
                            <view class="i-radio-title">其他证件</view>
                        </view>
                    </radio-group>
                </view>
            </i-cell>
            <div class="add-pic" v-if='currentType == idcard'>
                <div class="pic">
                    <img class="idcard-pic" v-if='!userInfo.ImageUrl' :src="idCardUrl" @click="addIdCard" alt="">
                    <img class="idcard-pic-pre" v-else :src="userInfo.ImageUrl" @click="perviewCard(userInfo.ImageUrl)" alt="">
                    <div class="upload-remove" v-if='userInfo.ImageUrl' @click="removeUserInfo"></div>
                </div>
            </div>
            <h4 class="w750">填写基本信息</h4>
            <i-panel title="基础用法" class="w750 content-item">
                <div class="i-cell i-input i-cell--required">
                    <div class="i-input-title">姓名</div>
                    <input class='i-input-input' type="text" v-model="userInfo.Name" placeholder="请输入姓名">
                </div>
                <!-- <i-input v-model="userInfo.Name" title="姓名" @click="changeName" required='required' placeholder="请输入姓名" /> -->
                <i-input v-model="userInfo.Sex" disabled="false" @click="openSex" title="性别" required='required' placeholder="请选择性别" />
                <!-- <i-cell title="性别"   required='required' v-model="userInfo.Sex" is-link></i-cell> -->
                <!-- <i-input v-model="userInfo.IdNo" type="number" @click="changeIdNo" required='required' title="证件号码" placeholder="请输入证件号码" /> -->
                <div class="i-cell i-input i-cell--required">
                    <div class="i-input-title">证件号码</div>
                    <input class='i-input-input' type="text" v-model="userInfo.IdNo" placeholder="请输入证件号码">
                </div>
            </i-panel>

            <div class="content-item">
                <!-- <i-input v-model="userInfo.Nation" @click="changeNation" title="民族" placeholder="请输入民族" /> -->
                <div class="i-cell i-input">
                    <div class="i-input-title">民族</div>
                    <input class='i-input-input' type="text" v-model="userInfo.Nation" placeholder="请输入民族">
                </div>
                <picker mode="date" v-model="userInfo.BirthDate" @change="bindTimeChange">
                    <view class="picker">
                        <!-- <i-cell title="出生年月" v-model="userInfo.BirthDate" is-link></i-cell> -->
                        <i-input v-model="userInfo.BirthDate" disabled="false" title="出生年月" placeholder="请选择出生年月" />
                    </view>
                </picker>
                <!-- <i-input v-model="phone" @change="changePhone" type="number" title="手机号码" placeholder="请输入手机号码" /> -->
                <div class="i-cell i-input">
                    <div class="i-input-title">手机号码</div>
                    <input class='i-input-input' type="number" v-model="phone" placeholder="请输入手机号码">
                </div>
            </div>
            <div class="content-item" style="display:none;">
                <i-cell title="住址" ></i-cell>
                <picker mode="region" @change="bindRegionChange" v-model="region">
                    <view class="picker">
                        <i-cell  is-link title="选择地址" v-model="region" ></i-cell>
                    </view>
                </picker>
                <textarea class="textarea" v-if="!showMask" v-model='userInfo.Address' placeholder="请输入详细地址" />
            </div>

            <h4 class="w750 shangbao"><img class="image" :src="shangbaoUrl"/>商保</h4>
            <div class="content-item">
                <picker @change="bindPlanPickerChange" v-model="planName" :range="planList" range-key="F_ProgramName">
                    <i-cell title="方案" required='required' v-model="planName" is-link></i-cell>
                </picker>
                <i-cell title="保费标准：" :label="insfee"></i-cell>
                <i-cell title="本次保费：" :label="totalFee"></i-cell>
                <picker mode="date" v-model="checkInDate" :start='checkInDateStart' @change="bindCheckInDateChange">
                    <view class="picker">
                        <i-input v-model="checkInDate" required='required' disabled="false" title="入保日期" placeholder="请选择入保日期" />
                    </view>
                </picker>
            </div>

            <h4 class="w750 shangbao" v-if="isShowSecurity"><img class="image" :src="shangbaoUrl"/>社保</h4>
            <div class="content-item" v-if="isShowSecurity">
                <i-cell title="社保情况"  @click="openShebao" v-model="hasSecurityText" is-link></i-cell>
                <picker mode="region" @change="bindWorkCityRegionChange" v-model="workCity">
                    <view class="picker">
                        <i-cell title="工作城市" v-model="workCity" is-link></i-cell>
                    </view>
                </picker>
                <picker mode="region" @change="bindSecurityRegionChange" v-model="securitycity">
                    <view class="picker">
                        <i-cell title="社保缴纳城市" v-model="securitycity" is-link></i-cell>
                    </view>
                </picker>
            </div>

            <div class="i-cell i-input i-cell--required content-item h50" v-if="planType === 'T004'">
                <div class="i-input-title">父母身份证号码</div>
                <input class='i-input-input' type="text" v-model="userInfo.parentIdNum" placeholder="请输入父母身份证号码">
            </div>

            <button class="submit" @click="_checkin">提交</button>
            <i-action-sheet :visible="sexVisible" :actions="sexActions" show-cancel @cancel="handleSexCancel" @select="handleSexClickItem" />
            <i-action-sheet :visible="shebaoVisible" :actions="shebaoActions" show-cancel @cancel="handleShebaoCancel" @select="handleShebaoClickItem" />
      </div>
  </div>
</template>

<script>
import idCardUrl from 'static/image/idCard.png'
import shangbaoUrl from 'static/image/shangbao.png'
import config from 'api/config'
import { getPlans, checkin, getInsFee } from 'api/api'
import { formatDate } from '@/utils/index'

const baseUrl =
    process.env.NODE_ENV === 'development'
        ? config.Host.development
        : process.env.NODE_ENV === 'production'
            ? config.Host.production
            : config.Host.test
// import { uploadIdCard } from 'api/api'
export default {
    data () {
        return {
            userInfo: {
                'Name': '',
                'Sex': '',
                'Address': '',
                'IdNo': '',
                'Nation': '',
                'BirthDate': '',
                'ImageUrl': '',
                'parentIdNum': ''
            },
            currentType: '1',
            idcard: '1',
            other: '0',
            idCardUrl,
            shangbaoUrl,
            planList: [],
            planName: '',
            planId: '',
            planType: '',
            insfee: '',
            totalFee: '',
            orgId: '',
            phone: '',
            region: [],
            securitycity: [],
            workCity: [],
            isShowSecurity: false,
            required: true,
            hasSecurity: false,
            hasSecurityText: '',
            sexVisible: false,
            sexActions: [
                {
                    id: 0,
                    name: '男',
                    value: '男'
                },
                {
                    id: 1,
                    name: '女',
                    value: '女'
                }
            ],
            shebaoVisible: false,
            shebaoActions: [
                {
                    id: 0,
                    name: '无',
                    value: false
                },
                {
                    id: 1,
                    name: '有',
                    value: true
                }
            ],
            showMask: false,
            checkInDate: '',
            checkInDateStart: ''
        }
    },

    methods: {
        cardChange (e) {
            this.currentType = e.mp.detail.value
        },
        bindTimeChange (e) {
            console.log(e)
            this.userInfo.BirthDate = e.mp.detail.value
            this.year = e.mp.detail.value
        },
        bindCheckInDateChange (e) {
            this.checkInDate = e.mp.detail.value
            this._getInsFee()
        },
        bindRegionChange (e) {
            console.log(e.mp.detail.value)
            this.region = e.mp.detail.value
        },
        bindSecurityRegionChange (e) {
            console.log(e.mp.detail.value)
            this.securitycity = e.mp.detail.value
            this._getInsFee()
        },
        bindWorkCityRegionChange (e) {
            this.workCity = e.mp.detail.value
            this._getInsFee()
        },
        handleShebaoCancel () {
            this.shebaoVisible = false
            this.showMask = false
        },
        handleSexCancel () {
            this.sexVisible = false
            this.showMask = false
        },
        openShebao () {
            this.shebaoVisible = true
            this.showMask = true
        },
        openSex () {
            this.sexVisible = true
            this.showMask = true
        },
        handleSexClickItem (e) {
            this.userInfo.Sex = this.sexActions[e.mp.detail.index].value
            this.sexVisible = false
            this.showMask = false
        },
        handleShebaoClickItem (e) {
            this.hasSecurityText = this.shebaoActions[e.mp.detail.index].name
            this.hasSecurity = this.shebaoActions[e.mp.detail.index].value
            this.shebaoVisible = false
            this.showMask = false
            this._getInsFee()
        },
        addIdCard () {
            let _this = this
            wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                    var tempFilePaths = res.tempFilePaths
                    // var tempFile = res.tempFiles[0]
                    console.log(res)
                    console.log(tempFilePaths)
                    wx.showToast({
                        title: '正在上传...',
                        icon: 'loading',
                        mask: true,
                        duration: 10000
                    })
                    wx.uploadFile({
                        url: `${baseUrl}/insurance/uploadidcard`,
                        filePath: tempFilePaths[0],
                        name: 'file',
                        header: {
                            'Authorization': wx.getStorageSync('token')
                        },
                        success: function (res) {
                            console.log(res)
                            _this.userInfo = JSON.parse(res.data).data
                            _this.userInfo.BirthDate = _this.userInfo.BirthDate.replace(/(\d{4})(\d{1,2})(\d{1,2})/, '$1-$2-$3')
                            _this.userInfo.Address = ''
                            wx.hideToast()
                        },
                        fail: function (res) {
                            wx.hideToast()
                            wx.showModal({
                                title: '错误提示',
                                content: '上传图片失败',
                                showCancel: false,
                                success: function (res) { }
                            })
                        }
                    })
                }
            })
        },
        perviewCard (e) {
            let urls = []
            urls.push(e)
            wx.previewImage({
                urls
            })
        },
        removeUserInfo () {
            this.userInfo = {
                'Name': '',
                'Sex': '',
                'Address': '',
                'IdNo': '',
                'Nation': '',
                'BirthDate': '',
                'ImageUrl': '',
                'parentIdNum': ''
            }
        },
        initDate () {
            this.removeUserInfo()
            this.region = []
            this.hasSecurityText = ''
            this.securitycity = []
            this.planName = ''
            this.planId = ''
            this.phone = ''
            this.hasSecurity = false
            this.insfee = ''
            this.totalFee = ''
            this.workCity = []
            this.planType = ''
        },
        _getPlans () {
            getPlans()
                .then(res => {
                    console.log(res)
                    let dateEnd = new Date(new Date().getFullYear(), 11, 31)
                    let dateBegin = new Date()
                    var dateDiff = dateEnd.getTime() - dateBegin.getTime() // 时间差的毫秒数
                    var dayDiff = Math.ceil(dateDiff / (24 * 3600 * 1000)) // 计算出相差天数
                    res.data.forEach(element => {
                        element.F_Insfee = element.F_Insfee.replace('&nbsp;', ' ')
                        let dayFee = Number(element.F_Insfee.replace('元/年/人', '')) / 365
                        element.totalFee = (dayFee * dayDiff).toFixed(2) + '元'
                    })
                    this.planList = res.data
                })
        },
        bindPlanPickerChange (e) {
            console.log(e.mp.detail.value)
            let index = e.mp.detail.value
            this.planName = this.planList[index].F_ProgramName
            this.planId = this.planList[index].F_Id
            this._getInsFee()
            this.insfee = this.planList[index].F_Insfee
            // this.totalFee = this.planList[index].totalFee
            this.planType = this.planList[index].F_Type
            if (this.planType === 'T001' || this.planType === 'T002') {
                this.isShowSecurity = false
            } else {
                this.isShowSecurity = true
            }
        },
        _checkin () {
            if (!this.userInfo.Name) {
                wx.showToast({
                    title: '请输入姓名',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            if (!this.userInfo.Sex) {
                wx.showToast({
                    title: '请选择性别',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            if (!this.userInfo.IdNo) {
                wx.showToast({
                    title: '请输入证件号码',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            if (!this.planId) {
                wx.showToast({
                    title: '请选择方案',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            if (!this.checkInDate) {
                wx.showToast({
                    title: '请选择入保日期',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            let obj = {
                'empName': this.userInfo.Name,
                'idNum': this.userInfo.IdNo,
                'nation': this.userInfo.Nation,
                'address': this.region.join(' ') + this.userInfo.Address,
                'orgId': '',
                'planId': this.planId,
                'phone': this.phone,
                'hasSecurity': this.hasSecurity,
                'securitycity': this.securitycity.join(' '),
                'workCity': this.workCity.join(' '),
                'parentIdNum': '',
                'checkInDate': this.checkInDate
            }
            if (this.planType === 'T001' || this.planType === 'T002') {
                obj.workCity = ''
                obj.securitycity = ''
            } else if (this.planType === 'T004') {
                obj.parentIdNum = this.parentIdNum
            }
            checkin(obj)
                .then(res => {
                    console.log(res)
                    if (res.state === 'success') {
                        wx.showToast({
                            title: res.message,
                            icon: 'success',
                            mask: true,
                            duration: 1000
                        })
                        this.initDate()
                    }
                })
        },
        _getInsFee () {
            getInsFee(this.planId, this.checkInDate, this.userInfo.IdNo, this.hasSecurity, this.securitycity.join(' '), this.workCity.join(' '))
                .then(res => {
                    console.log(res)
                    if (res.state === 'success') {
                        this.totalFee = res.data + '元'
                    } else {
                        wx.showToast({
                            title: res.message,
                            icon: 'none',
                            mask: true,
                            duration: 1000
                        })
                    }
                })
        }
    },
    async onShow () {
        this.checkInDateStart = formatDate(new Date(), 'YYYY-MM-DD')
        this.checkInDate = formatDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000), 'YYYY-MM-DD')
        await this._getPlans()
    }
}
</script>

<style lang='stylus'>
.getInsurance
    display: flex
    flex-direction: column
    align-items: center
    width: 100%
    overflow-x hidden
    .add-pic
        padding 25rpx 0
        display flex
        justify-content center
        background #fff
        width 100%
        .pic
            display flex
            width 428rpx
            height 270rpx
            justify-content center
            align-items center
            background #f2f2f2
            border-radius 5rpx
            position relative
            .idcard-pic
                width 198rpx
                height 115rpx
            .idcard-pic-pre
                width 100%
                height 100%
        .upload-remove
            width: 30rpx
            height: 30rpx
            position: absolute
            right: 12rpx
            top: 12rpx
            text-align: right
            vertical-align: top
            z-index: 2
            background-size: 30rpx auto
            background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='16' height='16' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Ccircle fill-opacity='.4' fill='%23404040' cx='8' cy='8' r='8'/%3E%3Cpath d='M11.898 4.101a.345.345 0 0 0-.488 0L8 7.511l-3.411-3.41a.345.345 0 0 0-.488.488l3.411 3.41-3.41 3.412a.345.345 0 0 0 .488.488L8 8.487l3.411 3.411a.345.345 0 0 0 .488-.488L8.488 8l3.41-3.412a.344.344 0 0 0 0-.487z' fill='%23FFF'/%3E%3C/g%3E%3C/svg%3E")
    .content-item
        background #fff
        width 100%
        padding 0 40rpx
        box-sizing border-box
    .cell-item
        display flex
        width 100%
        .footer
            display flex
            width 460rpx
            padding-left 15rpx
            .radio-item
                margin-right 45rpx
    .i-radio
        vertical-align: middle
    .i-radio-title
        display: inline-block
        vertical-align: middle
        color: #000
    .cell-group
        display flex
        width 100%
    .i-cell-ft
        color: #3395ff
    h4
        height 80rpx
        line-height 80rpx
        margin-left 50rpx
    .content-item
        width 100%
        margin-top 15rpx
    .textarea
        padding 20rpx 0 0 100rpx
        height: 70px
        background #fff
        display block
        color #007aff
    .submit
        box-sizing border-box
        width 88%
        border: none
        color #fff
        border-radius 8rpx
        background #007aff
        margin 42rpx 38rpx 72rpx
    .shangbao
        font-size 28rpx
        .image
            vertical-align middle
            width 28rpx
            height 28rpx
            margin-right 15rpx
    .h50
        height: 49px
</style>
